﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Microsoft.Samples.SqlServer;
using System.IO;

//********************************************************
//NOTE: this utility references the ServiceBrokerInterface
//This is part of the ServiceBroker

namespace Microsoft.Samples.SmartGrid.AMI.TestServiceBrokerQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection conn = null;
            SqlTransaction tran = null;
            Conversation dialog = null;
            Service client = null;
            string r = "Y";

            string connString = "Persist Security Info = False; Integrated Security = True; Initial Catalog = AMI; Data Source = .; Connect Timeout = 30;";

            conn = new SqlConnection(connString);
            conn.Open();

            while (r == "Y")
            {
                tran = conn.BeginTransaction();

                client = new Service("RawEventService", conn, tran);
                client.FetchSize = 1;

                dialog = client.BeginDialog("RawEventService", null, "DEFAULT", TimeSpan.FromMinutes(1), false, conn, tran);

                string outgoingBody = "";
                outgoingBody = outgoingBody + "<MeterEvent>";
                outgoingBody = outgoingBody + "  <TimeStamp>" + DateTime.Now.ToString() + "</TimeStamp>";
                outgoingBody = outgoingBody + "  <Type>HT</Type>";
                outgoingBody = outgoingBody + "  <Data>";
                outgoingBody = outgoingBody + "    <CurrentReading>145.67</CurrentReading>";
                outgoingBody = outgoingBody + "    <Temp>100.5</Temp>";
                outgoingBody = outgoingBody + "  </Data>";
                outgoingBody = outgoingBody + "  <MeterInfo>";
                outgoingBody = outgoingBody + "    <Number>1234</Number>";
                outgoingBody = outgoingBody + "    <VendorID>ABC</VendorID>";
                outgoingBody = outgoingBody + "    <HeadendID>XYZ</HeadendID>";
                outgoingBody = outgoingBody + "  </MeterInfo>";
                outgoingBody = outgoingBody + "</MeterEvent>";

                Message req = new Message("DEFAULT", new MemoryStream(Encoding.UTF8.GetBytes(outgoingBody)));

                dialog.Send(req, conn, tran);
                dialog.EndConversation(conn, tran);
                tran.Commit();

                Console.Write("Post another message Y/N: ");
                r=Console.ReadLine();
            }

            conn.Close();
        }
    }
}
